﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using InformationExtraction.Interface;
using InformationExtraction.Common;

namespace InformationExtraction
{
    class FileFeatureExtracter:IFileEnumerate
    {
        private IFeatureExtractable extracter = null;
        private InformationType targetType = InformationType.None;
        private StreamWriter featureWriter = null;

        public string FeatureFileName
        {
            get;
            set;
        }

        public FileFeatureExtracter(IFeatureExtractable fe)
        {
            extracter = fe;
            FeatureFileName = "feature.txt";
        }

        private void WriteFeatureLine(StreamWriter writer, Token token, List<int> features, InformationType target)
        {
            string featureLine = token.Type == targetType ? "1 " : "-1 ";

            int pos = 1;
            foreach (int df in features)
            {
                featureLine += pos.ToString() + ":" + df + " ";
                pos++;
            }

            writer.WriteLine(featureLine);
        }

        #region IFileEnumerate Members

        public void DoBeforeEnumerate()
        {
            if (extracter == null)
            {
                throw new Exception("No Feature Extraction Assigned!");
            }

            targetType = extracter.GetTargetType();
            featureWriter = new StreamWriter(FeatureFileName);

            
            System.Console.WriteLine("Information Extraction Start ...");
            System.Console.WriteLine("Extract Attribute Type: " + targetType.ToString());

        }

        public void DoForEachFile(FileInfo f)
        {
            FileParser parser = new FileParser();
            Document doc = parser.ParseFile(f);

            Token token = doc.BeginToken;

            List<int> featureVector = null;
            while (token != null)
            {
                featureVector = extracter.Extract(token);
                WriteFeatureLine(featureWriter, token, featureVector, targetType);
                token = token.Next;
            }
        }

        public void DoWhenComplete()
        {
            featureWriter.Close();

            System.Console.WriteLine("\nWriting feature data to " + FeatureFileName + "...");
            System.Console.WriteLine("Extraction Complete.");
        }

        public void SetOutputFile(string fileName)
        {
            FeatureFileName = fileName;
        }

        #endregion
    }
}
